<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    table {
        border-collapse: collapse;
        border-spacing: 0;
        border: 1px solid #c0c0c0;
        width: 500px;
        margin: 100px auto;
        text-align: center;
    }

    tr {
        /* background-color: #09c; */
        font: bold 10px 微软雅黑;
        color: #fff;
        height: 24px;
    }

    td {
        border: 1px solid #d0d0d0;
        color: #404060;
        padding: 10px;
    }

    .allCheck {
        width: 80px;
    }
</style>

<body>
    <table>
        <tr>
            <td class="allCheck">
                <input type="checkbox" id="checkAll"><span class="all">全选</span>
            </td>
            <td>商品</td>
            <td>商家</td>
            <td>价格</td>

        </tr>
        <tr>
            <td>
                <input type="checkbox" name="checkbox" class="ck">
            </td>
            <td>小米手机</td>
            <td>小米</td>
            <td>￥1999</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="checkbox" class="ck">
            </td>
            <td>小米手机</td>
            <td>小米</td>
            <td>￥1999</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="checkbox" class="ck">
            </td>
            <td>小米手机</td>
            <td>小米</td>
            <td>￥1999</td>
        </tr>
    </table>
    <script>
        let all = document.querySelector('#checkAll')
        let cks = document.querySelectorAll('.ck')
        let span = document.querySelector('.all')
        all.addEventListener('click', function () {
            // console.log(input.checked);
            cks.forEach(item => {
                item.checked = all.checked
            });
            if (all.checked) {
                span.innerHTML = '取消';
            } else {
                span.innerHTML = '全选'
            }
        })
        // 3.小按钮的做法，同时给多个元素绑定相同事件
        for (let i = 0; i < cks.length; i++) {
            // 绑定事件
            cks[i].addEventListener('click', function () {
                // console.log(11);
                // 只要点击任何一个小按钮，都要遍历所有的小按钮
                for (let j = 0; j < cks.length; j++) {
                    if (cks[j].checked === false) {
                        all.checked = false
                        // 如果有false 则退出循环 结束函数
                        return
                    }
                }
            // 当我们的循环结束，如果代码走到这里，说明没有false，就都被选中了
            all.checked = true
            span.innerHTML = '取消'
            })
        }
    </script>
</body>

</html>